package cn.kattomy.shop.category.adminaction;

import java.util.List;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.kattomy.shop.category.service.CategoryService;
import cn.kattomy.shop.category.vo.Category;
import cn.kattomy.shop.prevcategory.service.PrevCategoryService;
import cn.kattomy.shop.prevcategory.vo.PrevCategory;
import cn.kattomy.shop.utils.PageBean;

/**
 * 后台一级分类管理的 Action
 * @author kattomy
 *
 */
public class AdminCategoryAction extends ActionSupport implements ModelDriven<Category>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	//模型驱动使用的类
	private Category category = new Category();
	@Override
	public Category getModel() {
		return category;
	}

	//注入一级分类的 Service
	CategoryService categoryService;
	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}
	
	//注入前置分类的Service
	PrevCategoryService prevCategoryService;
	public void setPrevCategoryService(PrevCategoryService prevCategoryService) {
		this.prevCategoryService = prevCategoryService;
	}
	
	//当前页码
	private Integer pageNo;
	public Integer getPageNo() {
		return pageNo;
	}
	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}

	//后台执行查询所有一级分类的方法
	public String findAll(){
		//查询所有的一级分类
//		List<Category> cList = categoryService.getAll();
		PageBean<Category> pageBean = categoryService.findAll(pageNo);
		//将集合的数据显示到页面上
//		ActionContext.getContext().getValueStack().set("cList", cList);
		ActionContext.getContext().getValueStack().set("pageBean", pageBean);
		return "findAll";
	}
	
	//后台保存或修改一级分类的方法
	public String save(){
		//调用 Service 进行保存
		categoryService.save(category);
		return "saveSuccess";
	}
	
	public String update(){
		categoryService.update(category);
		return "updateSuccess";
	}
	
	//后台删除一级分类的方法
	public String delete(){
		//接收 cid，可以使用模型驱动，删除一级分类，同时删除二级分类。必须先根据 id 查询，再进行删除。
		category = categoryService.findByCid(category.getCid());
		System.out.println(category.getCid() + category.getCname() + category.getCategorySeconds().size());
		//删除
		categoryService.delete(category);
		//页面跳转
		return "deleteSuccess";
	}
	
	//后台编辑一级分类的方法
	public String edit(){
		category = categoryService.findByCid(category.getCid());
		List<PrevCategory> prevList = prevCategoryService.findAll();
		ActionContext.getContext().getValueStack().set("prevList", prevList);
		return "editSuccess";
	}
	
	//跳转至后台添加一级分类的方法
	public String add(){
		List<PrevCategory> prevList = prevCategoryService.findAll();
		ActionContext.getContext().getValueStack().set("prevList", prevList);
		return "add";
	}
}
